

//var lang = $('html').attr('lang'); //read the page attribute
// read from c#
// c0 , u, v, bFade, var imgRatio var initImg;
var imageSectionList = JSON.parse(myJson);
var imgWPercent = 1;
var imgOffset = 10;

//text properties
var textFont = "15px Tahoma, Arial";
var textColor = "#fff";
var textBkgColor = "#333333";
var textBkgStrip = 30;
var textOpacity = 0.7;
var textLine = '1';
var textStroke = '#333333';
var textOffsetX = 15;
var textOffsetY = 5;

var shadColor = '#666';
var shadBlur = 0;
var shadOffsetX = 0;
var shadOffsetY = 0;

//this instead of onload, cannot have multiple functions on onload
$(document).ready(init);
//window.onload = init;

function init() { 
    //define an array of the array images
    var sectionsInfo = new Array();
    for (k = 0; k < imageSectionList.length; k++) {
        var imgInfo = new Array();
        for (i = 0; i < imageSectionList[k].length; i++) {           
            imgInfo.push(new Array(imageSectionList[k][i].file, imageSectionList[k][i].link, imageSectionList[k][i].desc, imageSectionList[k][i].desc));
        }
        //add only if the section has images
        if (imgInfo.length > 0) {
            sectionsInfo.push(imgInfo);
        }
    }    
    Running(sectionsInfo);
}

function Running(imagesSecInfo) {    
    //use the timer   
    window.requestAnimFrame = (function () {
        return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    })();

    //this function updates the canvas content, adjusting the desired framerate
    var frame = 0;
    var msPerFrame = 1000 / 40;
    var lastUpdateTime = 0;
    var acDelta = 0;
    var delta = 0;
    function update() {
        requestAnimFrame(update);
        delta = Date.now() - lastUpdateTime;
        if (acDelta > msPerFrame) {
            acDelta = 0;
            redraw();           
            frame++;
        } else {
            acDelta += delta;
        }
        lastUpdateTime = Date.now();
    }
   
    var step; //section width
    var c; //clear   

    var oSectionImages = new Array();
    // create image object      
    function oImage() {
        this.image = null;
        this.x = 0;
        this.y = 0;
        this.x1 = 20;
        this.y1 = 20;
        this.width = 0;
        this.height = 0;
        this.w = 0; //original dimensions
        this.h = 0; //original dimensions
        this.url = "";
        this.text = "";  
    }
    
    var i = 0; //counter
    var k = 0; //counter
    var l = 0; //counter
    var m = 0;//counter 
   
   var w = Math.round(document.getElementById(divHtml).offsetWidth * imgWPercent-2*imgOffset);
   var h = Math.round(w/imgRatio);
   step = Math.round(w / (imageSectionList.length-1));
   c = 5;
   var secImgRatio = (step - c) / h;
     
    //set div height;    
    document.getElementById(divHtml).style.height = h + "px";   
    var containerDivExists=!!(document.getElementById("containerDiv"));
    if (!containerDivExists){
        var containerDiv = document.createElement('div');
        containerDiv.id = "containerDiv";
        containerDiv.style.position = "relative";
        containerDiv.style.width = w.toString()+"px";
        containerDiv.style.height = h.toString() + "px";
        containerDiv.style.left = "0px";
        containerDiv.style.top = "0px";
        document.getElementById(divHtml).appendChild(containerDiv);
    }

    for (i = 0; i < imagesSecInfo.length-1; i++) {      //0 section exluded 
        CreatePanels(i);
    }

    //show init image   
    var iniImg = new Image();
    iniImg.onload = function () {

        var wInit = 0;
        var hInit = 0;        

        if (this.height > this.width / imgRatio) {           
            if (this.width > w) {
            wInit = w;
            } else {
            wInit = this.width;
            }
            hInit = wInit / imgRatio;           
        } else {
           
            if (this.height > h) {
            hInit = h;
            } else {
            hInit = this.height;
            }
            wInit = hInit * imgRatio;
        }  

        for (i = 0; i < imageSectionList.length-1; i++) {
            var canvas = document.getElementById("canvasB" + i);
            var context = canvas.getContext("2d");
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.drawImage(iniImg, i * step * (wInit / w), 0, step * (wInit / w), hInit, 0, 0, step, h);
        }
        //start loading the rest images
        var oImages;
        l = 0 ; //don't load the 1st section
        browseSections(0);
    }
    iniImg.onerror = function () {
        alert("image " + image.src + " is missing");
    }

    //choose randomly from 0 section
    var randInit = Math.round(Math.random() * imagesSecInfo[0].length);
    iniImg.src = imagesSecInfo[0][randInit][0];
    //exlude 0 section, we don't need it any more    
    imagesSecInfo.splice(0, 1);    
   //start loading pictures
    function browseSections(l) {               
        oImages = new Array();
        k = 0;
        browseImages(k);        
    }

    function browseImages(i) {  
                  
        loadImage(imagesSecInfo[l][i][0], imagesSecInfo[l][i][1], imagesSecInfo[l][i][2]);
    }

    function loadImage(img, url, txt) {                              
        var myImage = new oImage();
        var image = new Image();
        image.onload = function () {
            myImage.w = this.width;
            myImage.h = this.height;
            if (this.height > this.width / secImgRatio) {
                if (this.width > w) {
                    myImage.width = w;
                } else {
                    myImage.width = this.width;
                }
                myImage.height = this.width / secImgRatio;
            } else {
                if (this.height > h) {
                    myImage.height = h;
                } else {
                    myImage.height = this.height;
                }
                myImage.width = myImage.height * secImgRatio;
            }

            if (k < imagesSecInfo[l].length - 1) {
                k++;
                browseImages(k);
            } else {
                oSectionImages.push(oImages);
                i = 0;
                k = 0;
                l++;               
                if (l < imagesSecInfo.length) {
                    browseSections(l);
                } else {                   
                    startApp()
                }
            }
        }

        image.onerror = function () {
            alert("image " + image.src + " is missing");
        }        
        image.src = img;
        image.id = k;
        myImage.image = image;
        myImage.url = url;
        myImage.text = txt;
        oImages.push(myImage); 
    }


    function startApp() {
        
        //pick random initial numbers    
        currentNo = new Array();
        for (k = 0; k < imagesSecInfo.length; k++) {
            currentNo.push(Math.floor(oSectionImages[0].length * Math.random()));
        }

        /*
        for (i = 0; i < imagesSecInfo.length; i++) {
            DrawBackPanel(i, oSectionImages[i][currentNo[i]]);
        }
        */

        for (i = 0; i < imagesSecInfo.length; i++) {
            ClearTiledContext(i);
        }        
       
        i = 0; //count frames
        k = -1; //count sections            

        update();               
    }
    
    //every time you call time function   
    function redraw() {
        //fade in phase
        if (i == 0) {
            //find next section numbers
            if (k < imagesSecInfo.length - 1) {
                k++;
            } else {
                k = 0;
            }

        } else if (i == c0 / 2) {
            //find next number
            if (currentNo[k] < oSectionImages[k].length - 1) {
                currentNo[k]++;
            } else {
                currentNo[k] = 0;
            }

            //draw new image in tiled panel            
            DrawTiledContext(k, oSectionImages[k][currentNo[k]]);
            ClearCaption(k);

            //find next number           
            if (currentNo[k] < oSectionImages[k].length - 1) {
                currentNo[k]++;
            } else {
                currentNo[k] = 0;
            }
           
        } else if (i == c0) {
            //draw new image in back panel            
            ClearTiledContext(k);            
            DrawBackPanel(k, oSectionImages[k][currentNo[k]]);
            WriteCaption(k, oSectionImages[k][currentNo[k]]);
            i = -1;                  
        }
        i++;
    }

    function DrawBackPanel(i, img) {
        var canvas = document.getElementById("canvasB" + i);
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);        
        context.drawImage(img.image, 0, 0, img.width, img.height, 0,0, step, h);
    }         
           
   
    function DrawTiledContext(i, img) {  
        for (m = 0; m < v; m++) {
            for (var n = 0; n < u; n++) {
                //alert("draw tiled context!");
                var canvasId = "tileCanvasA" + i.toString() + m.toString() + n.toString();                
                var canvas = document.getElementById(canvasId);
                var context = canvas.getContext("2d");
                //$("#"+ canvasId).hide();
                //alert((n / u) * step + "-" + (m / v) * h );
                context.drawImage(img.image, (n / u) * img.width, (m / v) * img.height, img.width / u, img.height / v,  (n/u)*step , (m / v) * h, step/u, h / v);
                //$("#" + canvasId).fadeIn();
                var r = Math.floor(Math.random()*2000);                
                //$("#" + canvasId).animate({ opacity:'1.0'}, 2000);                
                $("#" + canvasId).animate({ opacity:'1.0', height:h, left:'0px'}, r);
                               
            }                             
        }         
    }
       
    function ClearTiledContext(i) {
        for (m = 0; m < v; m++) {
            for (var n = 0; n < u; n++) {
                //var canvasId = tileCanvaces[m][n].id;
                var canvasId = "tileCanvasA" + i.toString() + m.toString() + n.toString();
                var canvas = document.getElementById(canvasId);
                var context = canvas.getContext("2d");
                //shuffle tiles...
                $("#" + canvasId).animate({ opacity: '0.0' }, 2000);
                //alert(bFade);                          
                if (bFade) {                                
                    if (Math.random() > 0.75) {
                        $("#" + canvasId).animate({ height: '-=150px', left: '100px' }, 0);
                    } else if (Math.random() > 0.50) {
                        $("#" + canvasId).animate({ height: '-=75px', left: '-100px' }, 0);
                    } else if (Math.random() > 0.25) {
                        $("#" + canvasId).animate({ height: '+=75px', left: '100px' }, 0);
                    } else {
                        $("#" + canvasId).animate({ height: '+=150px', left: '-100px' }, 0);
                    }
                   
                } 
            }
        }

    }  
      
    function WriteCaption(i, img) {
        var canvas = document.getElementById("canvasC" + i);
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        context.fillStyle = textBkgColor;        
        context.fillRect(imgOffset, h-textBkgStrip, step-c-imgOffset, textBkgStrip);
       
        context.fillStyle = textColor;
        context.fillText(img.text, textOffsetX, h - textBkgStrip + textOffsetY);
        
        canvas.removeEventListener('click', onClick, false);
        canvas.addEventListener('click', onClick, false);
        function onClick(e) {          
            var url = "";
            if (img.url.indexOf("http://") == -1) {
                url = hostURL + "default.aspx?" + "tabId=" + img.url;
                window.open(url, '_self', false);
            } else {
                url = img.url;
                window.open(url, '_blank', false);
            }
            
             //alert(url);
        }

    }

    function ClearCaption(i) {
        var canvas = document.getElementById("canvasC" + i);
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);              
    }


    function CreatePanels(i) {       
        var canvasBExists = !!document.getElementById("canvasB" + i);
        if (!canvasBExists) {
            var canvasB = document.createElement('canvas');
            var contextB = canvasB.getContext("2d");            
            canvasB.id = "canvasB" + i;
            canvasB.width = step-c;
            canvasB.height = h;
            canvasB.style.position = "absolute";
            canvasB.style.left = i * (step+c/2) + "px";
            canvasB.style.top = 0 + "px";
            document.getElementById("containerDiv").appendChild(canvasB);
            //create panel inside the div
        } 
        
        //this is not a canvas! this is a div!
        var canvasAExists = !!document.getElementById("canvasA" + i);
        if (!canvasAExists) {            
            var canvasA = document.createElement('div');
            //var contextA = canvasA.getContext("2d");           
            //var step = w / imageSectionList.length;           
            canvasA.id = "canvasA" + i;
            canvasA.width = step-c;
            canvasA.height = h;
            canvasA.style.position = "absolute";
            canvasA.style.left = i * (step + c / 2) + "px";
            canvasA.style.top =  "0px";           
            document.getElementById("containerDiv").appendChild(canvasA);
            //create panel inside the div
        }

        //all tile canvaces
        var tileCanvacesExists = !!(tileCanvaces);
        if (!secTileCanvaces) {
            var tileCanvaces = new Array();
        }

        //section tile canvaces
        var secTileCanvacesExists = !!(secTileCanvaces)
        if (!secTileCanvacesExists) {
            var secTileCanvaces = new Array();
        }

        //create tiles
        for (k = 0; k < v; k++) {
            var horTileCanvaces = new Array();
            var horTileContexts = new Array();
            for (l = 0; l < u; l++) {
                var canvasExists = !!document.getElementById("tileCanvasA" + i.toString() + k.toString() + l.toString());
                if (!canvasExists) {
                    var tileCanvas = document.createElement('canvas');
                    tileCanvas.id = "tileCanvasA" + i.toString() + k.toString() + l.toString();
                    tileCanvas.width = (step-c);
                    tileCanvas.height = h;
                    tileCanvas.style.position = "absolute";
                    tileCanvas.style.left = "0px";
                    tileCanvas.style.top = "0px"
                    document.getElementById("canvasA" + i.toString()).appendChild(tileCanvas);
                    var tileContext = tileCanvas.getContext("2d");
                    horTileCanvaces.push(tileCanvas);
                }
            }
            secTileCanvaces.push(horTileCanvaces);
        }
        tileCanvaces.push(secTileCanvaces);
                
        var canvasCExists = !!document.getElementById("canvasC" + i);
        if (!canvasCExists) {
            var canvasC = document.createElement('canvas');            
            contextC = canvasC.getContext("2d");
            canvasC.id = "canvasC" + i;
            canvasC.width = step-c;
            canvasC.height = h;
            canvasC.style.position = "absolute";
            canvasC.style.left = i * step+(c/2) + "px";
            canvasC.style.top = 0 + "px";
            document.getElementById("containerDiv").appendChild(canvasC);

            contextC.shadowColor = shadColor;
            contextC.shadowBlur = shadBlur;
            contextC.shadowOffsetX = shadOffsetX;
            contextC.shadowOffsetY = shadOffsetY;
            contextC.fillStyle = textColor;
            contextC.textBaseline = "top";
            contextC.font = textFont;
            contextC.globalAlpha = 0.7;
              
            canvasC.addEventListener('mouseover', onMouseOver, false);
            function onMouseOver(evt) {
                canvasC.style.cursor = "pointer";
            }
          /*
            canvasC.addEventListener('click', onClick, false);
            function onClick(e) {
                alert("clicked" + "-" + i);
                
                var url = "";
                if (img.url.indexOf("http://") == -1) {
                url = hostURL + "default.aspx?" + "tabId=" + img.url;
                } else {
                url = img.url;
                }
                window.open(url, '_self', false);
                
            }    
            */
        }

          

    }
   
}










  